<template>
  <view class="navigation">
    <view class="top-view">
				<eui-nav-bar ref="BcmNavBar" title="拣货任务" :storeName="sUserStoreName" :storeId="sUserStore"
					:option="nbOption" @menuFunc="onClickMenuFunc" @onClickStore="clickStore" color="#333"
					backgroundColor="white" rightIcon="">
					<template v-slot:right="">
						<view>
							<Status :status="workStatusInfo.workStatus" :onlineTime="workStatusInfo.onlineTime"
								@clickFunc="clickFunc" />
						</view>
					</template>
				</eui-nav-bar>
				<view style="background-color: #fff;" v-if="workStatusInfo.workStatus == '1'">
					<eui-search-bar v-model="searchValue" @confirm="searchConfirm" radius="100" leftIcon="icon-saoyisao"
						placeholder="请输入任务单号/订单号" @clear="clearSearch" @leftIconClick="clickScanLeft" :focus="true">
					</eui-search-bar>
				</view>
				<view class="container" v-if="workStatusInfo.workStatus == '1'">
					<scroll-view class="scroll-view" scroll-x scroll-with-animation scroll-animation-duration="240">
						<view :class="activeKey == item.value ? 'item on' : 'item'" v-for="(item, index) in statusList"
							:key="index" @click="changeTab(item.value)">
							<view class="name" style="font-size: 32rpx;">{{ item.text }}</view>
							<view class="border"
								:style="{ 'background': activeKey == item.value ? 'linear-gradient(159deg, #4FE0EA 0%, #85B6FD 100%)' : '#fff' }">
							</view>
							<view class="number" v-if="item.number > 0 && item.number < 100">{{ item.number }}</view>
							<view class="number" v-if="item.number >= 100">99+</view>
						</view>
					</scroll-view>
				</view>
			</view>
    <view class="main-view" :style="{ height: listHeight + 'rpx' }">
			<eui-virtual-list @onRefresh="listPullDown" @lower="listPullUp" refresher="true" isBottom="true"
				:origList="orderList" type="list" :showHeard="false" v-if="workStatusInfo.workStatus == '1'">
				<template v-slot:list="scope">
					<order-item :scope="scope" :current-time="currentTime"></order-item>
				</template>
				<template v-slot:bottom="scope">
					<view>
						<eui-button :modelValue="scope" title="打印" type="max2" class="margin"
							v-if="activeKey == '0' || activeKey == '1'" @buttonClick="printPickTask(scope)"
							single-tag="confrim"></eui-button>
						<eui-button :modelValue="scope" title="接单" type="max" class="margin" v-if="activeKey == '0'"
							@buttonClick="buttonClick" single-tag="confrim"></eui-button>
						<eui-button :modelValue="scope" title="开始拣货" type="max" class="margin" single-tag="picking"
							v-if="activeKey == '1'" @buttonClick="buttonClick"></eui-button>
						<eui-button :modelValue="scope" :title="scope.confluenceStatus != '1' ? '确认合流' : '查看详情'"
							:type="scope.confluenceStatus != '1' ? 'max' : 'max2'" class="margin" single-tag="submit"
							v-if="activeKey == '2'" @buttonClick="buttonClick"></eui-button>
					</view>
				</template>
			</eui-virtual-list>
			<view v-else class="white-view">
				<view style="width: 100%;height: 100%;flex-direction: column;" class="flex align-center">
					<image src="@/static/img/rdsImgs/quest_downline.png" mode="scaleToFill"
						style="width: 300rpx; height: 300rpx;margin-top: 300rpx;" />
					<text class="tips-level1">您当前处于下班状态</text>
					<text class="tips-level2">下班后将不再接到新任务提醒!</text>
					<eui-button type="base" title="我要上班" singleTag="online" @buttonClick="changeToOnline"
						style="margin-top: 20rpx;" />
				</view>
			</view>
		</view>
	</view>
</template>
<script setup type="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import service from '@/common/service';
import { getBcmUrl, bcmRequest } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictName, getBcmDictItem, formatPrice } from '../../../hooks/bcmUseUntils';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useMainStore } from "@/store/modules/store";
import { init, onClickRefresh, getWorkStatus } from '../../../hooks/bcmInit';
import Status from '../components/status.vue'
import Enjoy from "../../../common/enjoy"
import OrderItem from './components/OrderItem.vue'
import { usePrinterStore } from "@/store/printerStore";
import BluetoothPrinter from '@/common/BluetoothPrinter.js';
import { getPrintData } from '../utils/PrintFormatUtil.js'
import { storeToRefs } from "pinia";
import dateRangUtil from "@/common/dateRangUtil";
import BcmEventType from "@/pages/BcmViews/common/BcmEventType";

const mainStore = useMainStore();
const { loginInfo, setWorkStatus, setOnlineTime } = mainStore;
const bcmUrl = getBcmUrl();
const printerStore = usePrinterStore();
const { bluetoothPrinter } = storeToRefs(printerStore);

const BcmNavBar = ref(null);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');

const CurrentPage = ref(1); //第几页
const PageSize = ref(10); //每页10条
const RowsCount = ref(0); //总条数
const PageCount = ref(1); //总页数
const orderList = ref([]);
const searchValue = ref('');
const workStatusInfo = ref({
	workStatus: null,
	onlineTime: null
})

const nbOption = ref({
	items: [
		// {title: '我要收货', onClick: 'onClickNewCount', icon: 'plusempty'},
	]
})

const changeToOnline = async () => {
	service.enjoyShowLoading('正在加载...');
	let statusValue = workStatusInfo.value.workStatus == '1' ? '0' : '1', param = {
		userno: loginInfo.sUser,
		status: statusValue
	}
	const response = await bcmRequest(bcmUrl.stockApi, '用户表', 'SetStatus', param);
	service.enjoyHideLoading();
	setWorkStatus(statusValue)
	if (param.status == '1') {
		setOnlineTime(dateRangUtil.getCurrentTime())
	}
	workStatusInfo.value = {
		workStatus: statusValue,
		onlineTime: statusValue == '1' ? dateRangUtil.getCurrentTime() : null
	}
	if (statusValue == '1') {
		fetchOrderData();
		staOrderStatus();
	}
}

const clickFunc = () => {
	changeToOnline()
}

const onClickMenuFunc = (e) => {
	console.log('=====onClickMenuFunc: ', e);
	switch (e) {
		case 'onClickNewCount':
			//   setTimeout(() => {
			//     BcmNavBar.value.closeDrawer();
			//   },1200);
			//   uni.navigateTo({
			//     url: './edit?storeId=' + sUserStore.value
			//   });
			break;
	}
}

const statusList = ref([{
	text: '待接单',
	value: '0',
	number: 0
}, {
	text: '待拣货',
	value: '1',
	number: 0
}, {
	text: '已完成',
	value: '2',
	number: 0
}])

const activeKey = ref('0')

const timer = ref(null)
const chnlTypeList = ref([])
const currentTime = ref(null)

const startTimer = () => {
	stopTimer();
	timer.value = setInterval(() => {
		currentTime.value = new Date().getTime();
	}, 1000);
}

const stopTimer = () => {
	// 停止定时器
	clearInterval(timer.value);
	timer.value = null;
}

const changeTab = async (value) => {
	activeKey.value = value;
	orderList.value = [];
	fetchOrderData();
	staOrderStatus();
}

const setDefault = async () => {
	sUserStore.value = loginInfo?.sDefaultStore ? loginInfo.sDefaultStore : loginInfo.sUserStore;
	sUserStoreName.value = loginInfo?.sDefaultStoreName ? loginInfo.sDefaultStoreName : loginInfo.sUserStoreName;
	sUser.value = loginInfo.sUser;
	workStatusInfo.value = {
		workStatus: loginInfo.workStatus,
		onlineTime: loginInfo.onlineTime
	}
}

// 选择框点击事件
const clickStore = () => {
	if (workStatusInfo.value.workStatus == '1') {
		let parms = Enjoy.GetDialogParms();
		parms.CallBack = SelectionChanged;
		parms.SelectionType = "机构选择";
		parms.SelectedItems = sUserStore.value;
		Enjoy.OpenDialog(parms)
	} else {
		uni.showToast({ title: '当前已下班,请上班后切换～', icon: 'none' });
	}
}

const SelectionChanged = (event) => {
	if (event.SelectionType == '机构选择') {
		// 更新机构信息
		sUserStoreName.value = event.BackParms.Value;
		sUserStore.value = event.BackParms.Key;
		mainStore.switchStore(event.BackParms.Type, sUserStore.value, sUserStoreName.value);
		uni.$emit(BcmEventType.SWITCH_STORE, { msg: '切换门店' })
		// 按新条件获取数据
		fetchOrderData();
		staOrderStatus();
	}
}
// 列表下拉刷新
const listPullDown = (e) => {
	fetchOrderData();
	staOrderStatus();
}
// 列表上拉加载
const listPullUp = (e) => {
	if (CurrentPage.value < PageCount.value) {
		CurrentPage.value = CurrentPage.value + 1;
		fetchOrderData(true);
	}
}
const printPickTask = (e) => {
	let data = getPrintData(e, 'pickTask', null);
	BluetoothPrinter.setDevice(bluetoothPrinter.value).checkAndPrint(data).then((res) => {
		uni.showToast({ title: '打印完成' });
		console.log("BluetoothPrinter.checkAndPrint:then====>res", res);
	}).catch((res) => {
		console.log("BluetoothPrinter.checkAndPrint:catch====>res", res);
		uni.showModal({
			title: '打印失败',
			content: res.message,
			showCancel: false,
		})
	}).finally((res) => {
		uni.hideLoading();
	})
}
const buttonClick = (e) => {
	let { singleTag, modelValue } = e;
	switch (singleTag) {
		case 'confrim':
			orderAction({
				uniqueKey: '拣货任务表',
				methodName: 'PickTaskAcceptOrder'
			}, modelValue, undefined, '接单成功！')
			break;
		case 'picking':
			uni.navigateTo({
				url: './detail?id=' + modelValue.pickTaskNo + '&storeCode=' + sUserStore.value
			})
			break;
		case 'submit':
			uni.navigateTo({
				url: './detail?id=' + modelValue.pickTaskNo + '&storeCode=' + sUserStore.value
			})
			break;
	}
}

const searchConfirm = (e) => {
	searchValue.value = e.value;
	CurrentPage.value = 1;
	fetchOrderData()
	staOrderStatus()
}

const clearSearch = () => {
	searchValue.value = '';
	CurrentPage.value = 1;
	fetchOrderData()
	staOrderStatus()
}

const clickScanLeft = () => {
	uni.scanCode({
		success: async function (res) {
			if (res.result != '' && res.result != undefined && res.result != null) {
				searchValue.value = res.result;
				await searchConfirm({
					value: res.result
				});
			}
		}
	});
}

const orderAction = async ({
	uniqueKey,
	methodName
}, v, params = undefined, text = '', fn = undefined) => {
	service.enjoyShowLoading('正在加载...');
	let param = [{
		BillId: v.pickTaskId
	}]
	const response = await bcmRequest(bcmUrl.orderApi, uniqueKey, methodName, param);
	service.enjoyHideLoading();
	if (text) {
		uni.showToast({
			title: text,
			icon: 'none',
			duration: 2000
		});
	}
	await fetchOrderData();
	await staOrderStatus();
	if (fn) {
		fn(v)
	}
	if (params) {
		return response
	}
}

const fetchOrderData = async (e = undefined) => {
	service.enjoyShowLoading('正在加载...');
	if (!e) {
		CurrentPage.value = 1;
	}
	const param = {
		IsNotPage: false,
		CurrentPage: CurrentPage.value,
		PageSize: PageSize.value,
		extra: {
			isQueryDetail: false
		},
		WhereList: [
			{ c_col: "storeCode", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
			{ c_col: "status", c_oper: "等于", c_value: activeKey.value },
			{ c_col: "billNo", c_oper: "等于", c_value: searchValue.value }
		]
	}
	const response = await bcmRequest(bcmUrl.orderApi, '拣货任务表', 'QueryPickTaskList', param);
	service.enjoyHideLoading();
	CurrentPage.value = response.CurrentPage; //第几页
	PageSize.value = response.PageSize; //每页10条
	RowsCount.value = response.RowsCount; //总条数
	PageCount.value = response.PageCount; //总页数
	if (response.CurrentPage == 1) {
		orderList.value = response.ReturnObject;
	} else {
		orderList.value = orderList.value.concat(response.ReturnObject);
	}
}

const staOrderStatus = async () => {
	const response = await bcmRequest(bcmUrl.orderApi, '拣货任务表', 'PickTaskStatistics', {
		storeCode: sUserStore.value,
		billNo: searchValue.value
	});

	statusList.value.forEach(a => {
		let item = response.find(v => v.status == a.value)
		a.number = item?.num || 0
	})
}
let timeout;
const debounce = () => {
	if (timeout) {
		clearTimeout(timeout)
	}
	timeout = setTimeout(() => {
		changeTab(activeKey.value)
	}, 1000)
}

onMounted(() => {
	chnlTypeList.value = getBcmDictList('chnlType')

})

onShow(async () => {
	if (sUserStore.value && (workStatusInfo.value.workStatus == '1')) {
		await staOrderStatus();
		await fetchOrderData();
	}
})

onLoad(async () => {
	await init();
	setDefault();
	if (!loginInfo.sUserStore) {
		BcmNavBar.value.onClickStore();
		return;
	}
	startTimer()
	if (!!workStatusInfo.value?.workStatus) {
		if (workStatusInfo.value.workStatus == '1') {
			await staOrderStatus();
			await fetchOrderData();
		}
	} else {
		workStatusInfo.value.workStatus = await getWorkStatus()
	}
	uni.$on(BcmEventType.REFRESH_PICK_TASK_LIST, () => {
    debounce();
  })
})

onUnmounted(() => {
	stopTimer()
	uni.$off(BcmEventType.REFRESH_PICK_TASK_LIST)
})

defineExpose({
	SelectionChanged
})
</script>
<style lang="scss" scoped>
@import "../../../main.scss";
@import "../common/common.css";
.navigation {
  display: flex;
  height: 100vh;
  width: 100%;
  flex-direction: column;
  background: #F2F2F2;
}
.top-view {
  width: 100%;
  background: #FFFFFF;
}
.main-view {
  flex: 1;
  flex-direction: column;
}
.content {
	display: flex;
	box-sizing: border-box;
	overflow-x: hidden;
	width: 100%;
	height: 100%;

	//background-color: $uni-background;
	padding: 0;
}

.footer-view {
	height: 100%;
	background: $uni-bg-color;
}

::v-deep .white-main {
	right: 0;
	left: 0;
}

.on {
	color: rgba(2, 183, 230, 1);
	font-weight: bold;
}

.border {
	position: absolute;
	bottom: 0;
	left: 105rpx;
	width: 36rpx;
	height: 14rpx;
	border-bottom: none;
}

.content-img {
	position: relative;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: stretch;
	flex: 1;
	box-sizing: border-box;
	background-repeat: no-repeat;

	//background: $uni-background-img;
	background-size: 100% 150px;
}

.navigation {
	flex: 0 0 auto;
}

.m-list-template-list {
	.m-list-top {
		display: "block";
	}
}

.footer {
	flex: 1;
	box-sizing: border-box;
	padding: 0;
	margin: 0;
}

.bottom {
	display: flex;
	justify-content: space-between;
	flex: 0 0 auto;
	height: 70rpx;
	padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
	background: $uni-bg-color;
}

.bottom-1 {
	display: flex;
	justify-content: center;
	flex: 0 0 auto;
	height: 70rpx;
	padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
	background: $uni-bg-color;
	// border-top: 1rpx solid #979797;
}

// start 查询筛选
.search-fields {
	width: 100%;

	.center {
		margin: 0 10px;
	}

	.search-field {
		padding: 5px 0;
		margin: 5px 0;
	}

	::v-deep .m-card-input-content,
	::v-deep .m-input-input {
		height: 100%;
		text-align: right !important;

		uni-view,
		* {
			margin: 0 !important;
		}
	}
}

.order {
	flex: 1;

	::v-deep .m-list-template-list {
		.m-list-top {
			display: block;
		}
	}
}

.popup-content {
	display: flex;
	flex-direction: column;
	width: 100%;
	padding: 0;
	background-color: #fff;

	.popup-title {
		display: flex;
		align-items: center;
		box-sizing: border-box;
		width: 100%;
		height: 100rpx;
		padding-right: 36rpx;
		padding-left: 30rpx;
		font-size: 33rpx;
		line-height: 100rpx;
		border-bottom: 1px solid #f1f1f1;
	}

	textarea {
		box-sizing: border-box;
		width: 100%;
		height: 80px;
		padding: 5px;
		margin: 5px 0;
		border: 1px solid #ccc;
		border-radius: 5px;
	}
}

.container {
	box-sizing: border-box;
	width: 100%;
	height: 80rpx;
	color: #000;

	// padding: 0 20rpx 0 0;
	font-size: 14px;
	background-color: #fff;
	border-bottom: 2rpx solid #fff;
}

.scroll-view {
	display: flex;
	justify-content: space-around;
	align-items: center;
	box-sizing: border-box;
	overflow-x: auto;
	width: 100%;
	height: 100%;
	white-space: nowrap;
}

.item {
	position: relative;
	display: inline-block;
	box-sizing: border-box;
	width: 250rpx;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	text-align: center;
}

.number {
	position: absolute;
	top: 0;
	right: 10rpx;
	height: 30rpx;
	padding: 2px 6px;
	color: #fff;
	font-size: 12px;
	line-height: 30rpx;
	background-color: #f00;
	border-radius: 10px;
}

::v-deep .list_cell {
	padding-bottom: 14rpx;
  margin: 20rpx 20rpx 0;
}

.margin {
	margin: 0 15rpx !important;
}

.white-view {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: calc(100% - 20rpx);
	height: calc(100% - 20rpx);
	margin: 0 10rpx 10rpx 10rpx;
	color: $uni-text-color-hint;
	font-family: $uni-font-family;
	font-size: $uni-font-size-level3;
	font-style: normal;
	font-weight: $uni-font-weight-level1;
	line-height: 40rpx;
	background: $uni-bg-color-inverse;
	border-radius: 20rpx;
}

::v-deep .status-view {
	background-color: #02b7e6;
}
</style>
